const path = require('path')
// 代码压缩
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

// gzip压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const isProduction = process.env.NODE_ENV !== 'development'

function resolve(dir) {
  return path.join(__dirname, dir)
}
// 本地环境是否需要使用cdn
const devNeedCdn = false
const vueV = require('vue/package.json').version
const routerV = require('vue-router/package.json').version
const vuexV = require('vuex/package.json').version
const axiosV = require('axios/package.json').version
const elementV = require('element-ui/package.json').version

// cdn链接
const cdn = {
  // cdn：模块名称和模块作用域命名（对应window里面挂载的变量名称）
  externals: {
    'vue': 'Vue',
    'vuex': 'Vuex',
    'vue-router': 'VueRouter',
    'axios': 'axios',
    'element-ui': 'ELEMENT',
    'js-cookie': 'Cookies',
    'echarts': 'echarts',
      'AMap': "AMap", // 高德地图配置
  },
  // cdn的css链接
  css: [
    `https://cdn.bootcss.com/element-ui/${elementV}/theme-chalk/index.css`,
  ],
  // cdn的js链接
  js: [
    `https://cdn.bootcss.com/vue/${vueV}/vue.min.js`,
    `https://cdn.bootcss.com/vuex/${vuexV}/vuex.min.js`,
    `https://cdn.bootcss.com/vue-router/${routerV}/vue-router.min.js`,
    `https://cdn.bootcss.com/element-ui/${elementV}/index.js`,
    `https://lib.baomitu.com/echarts/4.5.0/echarts.min.js`,
    `https://cdn.bootcss.com/axios/${axiosV}/axios.min.js`

  ]
}
module.exports = {
  publicPath: "/",
  productionSourceMap: false,
  chainWebpack: (config) => {
    config.resolve.alias
      .set('@/', resolve('src'))
    // config.module.rule('images').test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
    config.module.rule('images').test(/\.(png|jpe?g|gif)(\?.*)?$/)
      .use('image-webpack-loader')
      .loader('image-webpack-loader')
      .options({
        bypassOnDebug: true
      }).end()
    config.plugin('html').tap(args => {
      // 生产环境或本地需要cdn时，才注入cdn
      if (isProduction || devNeedCdn) args[0].cdn = cdn
      return args
    })


    // config.plugins.delete('prefetch')
  },
  configureWebpack: config => {
        // 生产环境相关配置

    // 用cdn方式引入，则构建时要忽略相关资源
    if (isProduction || devNeedCdn) config.externals = cdn.externals
    if (isProduction) {
      // 代码压缩
      config.plugins.push(
        new UglifyJsPlugin({
          uglifyOptions: {
            //生产环境自动删除console
            compress: {
              //warnings: false, // 若打包错误，则注释这行
              drop_debugger: true,
              drop_console: true,
              pure_funcs: ['console.log']
            }
          },
          sourceMap: false,
          parallel: true
        })
      )
      // gzip压缩
      const productionGzipExtensions = ['js', 'css']
      config.plugins.push(
        new CompressionWebpackPlugin({
          filename: '[path].gz[query]',
          algorithm: 'gzip',
          test: new RegExp(
            '\\.(' + productionGzipExtensions.join('|') + ')$'
          ),
          threshold: 1024, // 只有大小大于该值的资源会被处理 10240
          minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
          deleteOriginalAssets: false // 删除原文件
        })
      )
                  // 公共代码抽离
                  config.optimization = {
                    splitChunks: {
                        cacheGroups: {
                            vendor: {
                                chunks: 'all',
                                test: /node_modules/,
                                name: 'vendor',
                                minChunks: 1,
                                maxInitialRequests: 5,
                                minSize: 0,
                                priority: 100
                            },
                            common: {
                                chunks: 'all',
                                test: /[\\/]src[\\/]js[\\/]/,
                                name: 'common',
                                minChunks: 2,
                                maxInitialRequests: 5,
                                minSize: 0,
                                priority: 60
                            },
                            styles: {
                                name: 'styles',
                                test: /\.(sa|sc|c)ss$/,
                                chunks: 'all',
                                enforce: true
                            },
                            runtimeChunk: {
                                name: 'manifest'
                            }
                        }
                    }
                }
    } else{
        config.externals = {
            AMap: "AMap", // 高德地图配置
        };
    }
  },

  // transpileDependencies: ['*'],
  css: {
    loaderOptions: {
      less: {
        modifyVars: {},
        javascriptEnabled: true,
      }
    }
  },


  devServer: {
    port: 3000,
    proxy: {
      '/api': {
        target: process.env.VUE_APP_SERVER_URL,
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      },
      '/userfiles': {
        target: process.env.VUE_APP_SERVER_URL,
        changeOrigin: true,
        pathRewrite: {
          '^/userfiles': '/userfiles'
        }
      }
    },
    disableHostCheck: true,
    open: true
  },

  lintOnSave: false
}
